import React from 'react';
import { connect } from 'dva';
import { withRouter } from 'dva/router';
import { Layout } from 'antd';
import MainSideber from './MainSideber';
import MainHeader from './MainHeader';
import MainContent from './MainContent';
import styles from './Main.css'

class Main extends React.PureComponent {
    UNSAFE_componentWillMount() {
        this.routerSwitch()
    }
    UNSAFE_componentWillUpdate(nextProps, nextState) {
        this.routerSwitch()
    }
    routerSwitch() {
        const userinfo = this.props.userinfo.userinfo
        const history = this.props.history
        let userinfo_length = Object.keys(userinfo)
        switch (userinfo_length.length) {
            case 0:
                history.replace('/login')
                break;
            default:
                break;
        }
    }

    get sideberProps() {
        const { dispatch, history } = this.props
        const { theme, collapsed, defaultSelectedKeys, defaultOpenKeys } = this.props.theme
        const { menuList } = this.props.userinfo
        return {
            theme,
            history,
            collapsed,
            defaultSelectedKeys,
            defaultOpenKeys,
            menuList,
            menuClick: e => {
                dispatch({
                    type: 'theme/menuClick',
                    data: e.keyPath
                })
            },
            changeTheme: checked => {
                dispatch({
                    type: 'theme/changeTheme',
                    data: checked === true ? 'dark' : 'light'
                })
            }
        }
    }


    render() {
        const { theme, dispatch } = this.props
        const userinfo = this.props.userinfo.userinfo
        return (
            <Layout>
                {Object.keys(userinfo).length !== 0 ?
                    <>
                        <MainSideber {...this.sideberProps} className={styles.containerLeft} />
                        <Layout className={styles.containerRight}>
                            <MainHeader collapsed={theme.collapsed} dispatch={dispatch} />
                            <MainContent {...this.props} />
                        </Layout>
                    </>
                    :
                    ''
                }

            </Layout>
        );
    }
}

const mapStateToProps = state => {
    return {
        theme: state.theme,
        userinfo: state.userinfo
    }
}
export default withRouter(connect(mapStateToProps)(Main));